package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.CartConstant;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.common.vo.WeiBoResponseVo;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;

@RestController
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session, HttpServletRequest request){
//        根据code获取accessToken
        String url = "http://api.weibo.com/oath2/access_token";
        HashMap<String, String> map = new HashMap<>();
        map.put("code",code);
        map.put("client_id","clientID");
        map.put("client_secret","secret");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","uri");
        String s = HttpUtils.sendPost(url, map);
        if(s!=null){
            WeiBoResponseVo vo = JSON.parseObject(s, WeiBoResponseVo.class);
            R r = memberFeignService.weiboLogin(vo);
            MemberRespVo data = r.getData(new TypeReference<MemberRespVo>() {});

            session.setAttribute(CartConstant.LOGIN_USER,data);
        }

//        登陆成功跳回首页`
        return "获取授权成功";
    }
}
